<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto">
        <!-- 使用row和col实现一行两列布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品选择" prop="productId">
              <el-select v-model="formData.productId" placeholder="请选择产品" filterable remote
                :remote-method="remoteMethod" clearable @change="handleProductSelect" style="width: 100%">
                <el-option v-for="product in productList" :key="product.id" :label="product.productName"
                  :value="product.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺路线名称" prop="processRouteName">
              <el-input v-model="formData.processRouteName" placeholder="请输入工艺路线名称" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工艺路线类型" prop="routeType">
              <el-select v-model="formData.routeType" placeholder="请选择工艺路线类型" style="width: 100%"
                @change="handleRouteTypeChange">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ROUTE_TYPE)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="parseInt(dict.value)"
                  :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ProcessRouteApi from '@/api/basic/processroute';
import * as ProductApi from '@/api/basic/product/index.js';
import { getDictDatas,getDictDataLabel, DICT_TYPE } from '@/utils/dict'
export default {
  name: "ProcessRouteForm",
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 产品列表数据
      productList: [],
      // 表单参数
      formData: {
        id: undefined,
        productId: undefined,
        productName: undefined,
        productCode: undefined,
        processRouteName: undefined,
        routeType: undefined,
        routeTypeName: undefined,
        status: 1
      },
      // 加载状态
      loadingProduct: false,
      // 表单校验
      formRules: {
        productId: [{ required: true, message: '产品不能为空', trigger: 'change' }],
        routeType: [{ required: true, message: '工艺路线类型不能为空', trigger: 'change' }],
        routeTypeName: [{ required: true, message: '工艺路线类型名称不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 初始化产品列表数据
    this.getProductList();
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ProcessRouteApi.getProcessRoute(id);
          this.formData = res.data;
          this.dialogTitle = "修改工艺路线";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增工艺路线";
      }
    },
    /** 获取产品列表 */
    async getProductList() {
      try {
        const res = await ProductApi.getProductPage({
          pageNo: 1,
          pageSize: 100 // 获取足够多的产品数据
        });
        this.productList = res.data.list;
      } catch (error) {
        this.$modal.msgError('获取产品列表失败');
      }
    },
    /** 处理产品选择 */
    handleProductSelect(productId) {
      const selectedProduct = this.productList.find(product => product.id === productId);
      if (selectedProduct) {
        this.formData.productName = selectedProduct.productName;
        this.formData.productCode = selectedProduct.productCode;
      } else {
        this.formData.productName = undefined;
        this.formData.productCode = undefined;
      }
    },

    /** 远程搜索产品 */
    async remoteMethod(query) {
      if (!query) {
        // 如果查询条件为空，加载默认产品列表
        this.getProductList();
        return;
      }

      this.loadingProduct = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          productName: query // 假设API支持按产品名称搜索
        };
        const res = await ProductApi.getProductPage(params);
        this.productList = res.data?.list || [];
      } catch (error) {
        console.error('远程搜索产品失败:', error);
        this.$modal.msgError('搜索产品失败');
      } finally {
        this.loadingProduct = false;
      }
    },


    /** 处理工艺路线类型选择 */
    handleRouteTypeChange(routeType) {
      this.formData.routeTypeName = this.getDictDataLabel(DICT_TYPE.ROUTE_TYPE, routeType);
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ProcessRouteApi.updateProcessRoute(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ProcessRouteApi.createProcessRoute(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        productId: undefined,
        productName: undefined,
        productCode: undefined,
        processRouteName: undefined,
        routeType: undefined,
        routeTypeName: undefined,
        status: 1,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
